package fr.uniscol.view;

import java.io.File;
import java.util.HashMap;
import java.util.Locale;

import java.util.Map;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.view.AbstractUrlBasedView;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

public class CustomInternalResourceViewResolver extends InternalResourceViewResolver {

	public static final Logger log = Logger.getLogger(CustomInternalResourceViewResolver.class);
	
	private String includes = "";
	
	private String template = "";

    public String getIncludes() {
		return includes;
	}

	public void setIncludes(String includes) {
		this.includes = includes;
	}
	
	public String getTemplate() {
        log.debug("getTemplate():" + template);
		return template;
	}

	public void setTemplate(String template) {
		this.template = template;
	}

	@Override
	protected AbstractUrlBasedView buildView(String viewName) throws Exception {
		
        log.debug("buildView(" + viewName + ")");
        
		AbstractUrlBasedView view = null;
		
		File f = new File(getServletContext().getRealPath(getPrefix() + viewName + getSuffix()));
		log.debug("JSP: " + f.getAbsolutePath() + ": " + f.exists());
		
		if(!f.exists()){
			// On tente de rechercher la vue parmi les vues incluses
			f = new File(getServletContext().getRealPath(getIncludes() + viewName + getSuffix()));
			log.debug("JSP Incluse: " + f.getAbsolutePath() + ": " + f.exists());
			
			if(f.exists()){
				getAttributesMap().put("viewInclude", getIncludes() + viewName + getSuffix());
				view = super.buildView(getTemplate());
				
			}else{
				throw new Exception("Impossible de trouver la vue: " + viewName);
			}
			
		}else{
			// Vue standard
			view = super.buildView(viewName);
		}
		
		return view;
	}
}
